import { useToast } from '@/plugins/toast/api'
import router from '@/router'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'

export default class Request {
	static posUrl(url: string): boolean {
		/* 判断url是否为绝对路径 */
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
	}

	request<T>(options: AxiosRequestConfig): Promise<AxiosResponse<T>> {
		const instance = axios.create()

		// 添加请求拦截器
		instance.interceptors.request.use(
			function (config) {
				// 在发送请求之前做些什么
				const token = localStorage.getItem('token')
				// console.log("---------request---------");
				// console.log(token);
				// console.log("---------request---------");

				if (token) {
					config.headers['Authorization'] = `Bearer ${token}`
					config.headers['Accept'] = 'application/json'
					// config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
					// store.dispatch('logined', localStorage.token)
				}
				return config
			},
			function (error) {
				// 对请求错误做些什么
				return Promise.reject(error)
			}
		)

		// 添加响应拦截器
		instance.interceptors.response.use(
			function (response) {
				// 对响应数据做点什么
				// console.dir(`response ${response}`);
				return response
			},
			function (error) {
				// 对响应错误做点什么
				console.dir(error)
				if (error.response.status === 401) {
					window.localStorage.clear()
					router.push('/login')
				} else if (error.response.status === 404) {
					useToast({
						type: 'fail',
						text: '用户名或密码错误'
					})
				} else {
					useToast({
						type: 'fail',
						text: error.message
					})
				}
				return Promise.reject(error)
			}
		)

		return instance.request<T>({
			...options
		})
	}

	get<T = any>(url: string, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			method: 'get',
			...options
		})
	}

	post<T = any>(url: string, data?: any, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			data,
			method: 'post',
			...options
		})
	}

	put<T = any>(url: string, data?: any, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			data,
			method: 'put',
			...options
		})
	}

	delete<T = any>(
		url: string,
		data: any = {},
		options: AxiosRequestConfig = {}
	) {
		return this.request<T>({
			url,
			data,
			method: 'DELETE',
			...options
		})
	}
}
